package com.yundasys.lab12java.singleton;

/**
 * @PACKAGE_NAME: com.yundasys.lab12java.singleton
 * @NAME: SingletonDemo
 * @USER: jiangta
 * @DATE: 2023/1/18
 * @TIME: 9:04 上午
 * @PROJECT_NAME: springboot-labs
 */
public class SingletonDemo {

    private static SingletonDemo instance = null;

    private SingletonDemo() {
        System.out.println(Thread.currentThread().getName() + "\t 我是构造方法SingletonDemo");
    }

    public static SingletonDemo getInstance() {
//        if(instance ==null) {
//            instance = new SingletonDemo();
//        }
        /**
         * 通过引入DCL Double Check Lock 双端检锁机制
         *
         * 就是在进来和出去的时候，进行检测
         */
        if(instance ==null) {
            synchronized (SingletonDemo.class) {
                if(instance ==null) {
                    instance = new SingletonDemo();
                }
            }
        }

        return instance;
    }

    public static void main(String[] args) {
        // 这里的 == 是比较内存地址
        /**单线程情况
        System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance());
        System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance());
        System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance());
        System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance());
         */

        for(int i=0;i<10;i++){
            new Thread(()->{
                SingletonDemo.getInstance();
            }, String.valueOf(i)).start();
        }
    }
}
